package handler

import (
	"github.com/gin-gonic/gin"
	"github.com/lab-online/internal/user/constant"
	"github.com/lab-online/internal/user/entity"
	mw "github.com/lab-online/pkg/middleware"
	"github.com/lab-online/pkg/resp"
)

type LoginReqBody struct {
	Username string `json:"username" binding:"required,max=10,min=3" example:"20240126"` // 学号或者工号
	Password string `json:"password" binding:"required,max=64,min=8" example:"12345678"` // 密码
}

var LoginValidator = mw.NewValidator(func() *mw.ValidatorOptions {
	return &mw.ValidatorOptions{
		Body: &LoginReqBody{},
	}
})

type Token struct {
	AccessToken
	RefreshToken string `json:"refreshToken" binding:"required" example:"token"` // 刷新令牌
}
type LoginRespBody struct {
	resp.BaseRespBody
	Data *Token `json:"data" binding:"required"`
}

// Login
//
//	@Summary				用户登录
//	@Description.markdown	Login
//	@Tags					user
//	@Accept					json
//	@Produce				json
//	@Param					Body	body		LoginReqBody	true	"JSON 请求体"
//	@Success				200		{object}	LoginRespBody
//	@Failure				400		{object}	resp.FailedRespBodyString
//	@Router					/v1/users/login [post]
func (h *Handler) Login(c *gin.Context) {
	user := c.MustGet(mw.KeyBody).(*LoginReqBody)

	// TODO 限制登录次数

	userEntity := entity.NewUserEntity(
		entity.WithUsername(user.Username),
		entity.WithPassword(user.Password),
	)

	if accessToken, refreshToken, err := h.domain.Login(userEntity); err != nil {
		resp.ErrorHandler(c, err)
	} else {
		resp.Success(c, constant.CodeSuccessLogin, &Token{
			AccessToken{accessToken},
			refreshToken,
		})
	}
}
